//
//  ConversionOptionController.swift
//  SCA
//
//  Created by tjun on 2025/9/23.
//

import UIKit

class ConversionOptionController: UIViewController {
    
    private var maskView: UIButton!
    private var contentView: UIView!
    private let datas: [ConversionOptionModel]
    
    private let moveDistance: CGFloat = 50
    private var onSelectOption: ((ConversionOptionModel) -> Void)?
    
    private lazy var tableView: UITableView = {
        
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColorMake(0x2E3036)
        tableView.rowHeight = 36
        tableView.separatorStyle = .none
        tableView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
        tableView.contentInsetAdjustmentBehavior = .never;
        tableView.register(ConversionOptionCell.self, forCellReuseIdentifier: ConversionOptionCell.identifier)
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        return tableView
    }()
    
    init(datas: [ConversionOptionModel], onSelectOption: ((ConversionOptionModel) -> Void)?) {
        self.datas = datas
        self.onSelectOption = onSelectOption
        super.init(nibName: nil, bundle: nil)
        self.modalPresentationStyle = .custom
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func showIn(_ controller: UIViewController) {
        controller.present(self, animated: false, completion: nil)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .clear
        
        maskView = UIButton(frame: view.bounds).addTo(view)
        maskView.addTarget(self, action: #selector(maskViewTapped), for: .touchUpInside)
        maskView.backgroundColor = .black.withAlphaComponent(0)
        
        var contentW = view.width - 150
        datas.forEach { model in
            let textW = model.value.getSize(maxWidth: view.width - AppStyle.margin.left * 2 - 50, font: UIFontMake(16)).width
            if textW + 44 > contentW {
               contentW = textW + 50
           }
        }
        
        let maxContentH = screenHeight * 0.5
        var contentH = maxContentH
        
        contentView = UIView().addTo(view)
        contentView.backgroundColor = UIColorMake(0x2E3036)
        contentView.addCorner(radius: 15)
        
        tableView.addTo(contentView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        let maxShowCount = (screenHeight - navBarHeight) / self.tableView.rowHeight - 5
        
        contentH = min(maxShowCount * self.tableView.rowHeight, CGFloat(datas.count) * self.tableView.rowHeight) + tableView.contentInset.top + tableView.contentInset.bottom
        contentView.frame = CGRectMake((view.width - contentW) * 0.5, -contentH , contentW, contentH)
        
        contentView.y = (self.view.height - self.contentView.height) * 0.5 - 35 - moveDistance
        contentView.alpha = 0
    }
    
    @objc private func maskViewTapped() {
        dismiss(completion: nil)
    }
    
    private func dismiss(completion: (() -> Void)? = nil) {
        UIView.animate(withDuration: 0.25) {
            self.contentView.alpha = 0
            self.maskView.backgroundColor = .black.withAlphaComponent(0)
            self.contentView.y = self.contentView.y - self.moveDistance
        } completion: { finishi in
            self.dismiss(animated: false, completion: completion)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        UIView.animate(withDuration: 0.65, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.7, options: .curveEaseIn) {
            self.contentView.alpha = 1
            self.maskView.backgroundColor = .black.withAlphaComponent(0.5)
            self.contentView.y = self.contentView.y + self.moveDistance
        }
    }
    
}


extension ConversionOptionController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: ConversionOptionCell.identifier, for: indexPath) as! ConversionOptionCell
        cell.model = datas[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        datas.forEach { $0.isSelected = false }

        let model = datas[indexPath.row]
        model.isSelected.toggle()
        tableView.reloadData()
        
        onSelectOption?(model)
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: {
            self.dismiss()
        })
        
    }
    
}
